
Partial Class DatabaseE
    Inherits System.Web.UI.Page

    Private moServer As SQLAutoDocLib.Server = Nothing
    Private moDatabase As SQLAutoDocLib.Database = Nothing

    Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
        If IsPostBack = False Then
            '---Initialize page
            Dim sSID As String = Request.QueryString("S")
            Dim sDID As String = Request.QueryString("D")
            Dim sDREVID As String = Request.QueryString("DV")

            '---Load server info
            moServer = New SQLAutoDocLib.Server(sSID)
            moServer.Load()

            SID.Value = sSID
            lblServerName.Text = moServer.Name

            If Not IsNumeric(sDID) Then
                '--Add
                trCS.Visible = False

            Else
                '---Load database revs
                Dim oDatabaseFactory As New SQLAutoDocLib.Database_Factory
                DBREVID.DataSource = oDatabaseFactory.GetAllRevsForDatabase(sDID)
                DBREVID.DataValueField = "REVID"
                DBREVID.DataTextField = "REVDATE"
                DBREVID.DataBind()

                '--Edit
                moDatabase = New SQLAutoDocLib.Database(sDID, sDREVID)
                moDatabase.Load()

                DID.Value = sDID
                DBREVID.Value = sDREVID

                txtName.Text = moDatabase.Name
                txtDesc.Text = moDatabase.Desc
                chkIsActive.Checked = moDatabase.IsActive

                trCS.Visible = True

            End If

            SetScanIntervals()

        ElseIf hidToolbarAction.Value = "Delete" Then
            Dim oDatabaseFactory As New SQLAutoDocLib.Database_Factory
            For Each oDatabase As SQLAutoDocLib.Database In oDatabaseFactory.GetAllRevsForDatabase(DID.Value)
                oDatabase.IsDeleted = True
                oDatabase.Save()
            Next

            Response.Redirect("SQServerE.aspx")

        ElseIf ValidateFields() Then
            '--Update
            If Not IsNumeric(DID.Value) Then
                '---Add
                moDatabase = New SQLAutoDocLib.Database
                moDatabase.ServerID = SID.Value
                moDatabase.Name = txtName.Text
                moDatabase.Desc = txtDesc.Text
                moDatabase.IsActive = chkIsActive.Checked
                moDatabase.ConnectionString = MakeConnectionString()

                moDatabase.Rev()
            Else
                '---Edit
                moDatabase = New SQLAutoDocLib.Database(DID.Value, DBREVID.Value)
                moDatabase.Load()

                moDatabase.Name = txtName.Text
                moDatabase.Desc = txtDesc.Text
                moDatabase.IsActive = chkIsActive.Checked

                Dim sConnectionString As String = MakeConnectionString()
                If sConnectionString > "" Then
                    '---Only set connection string if it has been modified
                    moDatabase.ConnectionString = MakeConnectionString()
                End If

                moDatabase.Save()
            End If

            SaveScanIntervals()

            If hidToolbarAction.Value = "XML" Then
                Dim oGUID As Guid = Guid.NewGuid
                Dim sPath As String = Application("TempPath") & oGUID.ToString & ".xml"
                Dim oText As New System.IO.StreamWriter(sPath)
                oText.Write(moDatabase.ToXML)
                oText.Flush()
                oText.Close()
                oText.Dispose()

                Dim sURL As String = Session("TempURL") & oGUID.ToString & ".xml"
                Response.Redirect(sURL)

            ElseIf hidToolbarAction.Value = "Scan" Then
                Dim oScanner As New SQLAutoDocLib.Scanner
                oScanner.Immediate_ScanDatabase(moDatabase.ID)
            End If

            hidRefreshParent.Value = "yes"
        End If
    End Sub

    Private Sub SetScanIntervals()
        Dim oIntervalFactory As New SQLAutoDocLib.ScanSchedule_Factory
        Dim oQueueFactory As New SQLAutoDocLib.ScanQueue_Factory

        Dim lDatabaseID As Long = SQLAutoDocLib.Database.NODATA
        If Not moDatabase Is Nothing Then
            lDatabaseID = moDatabase.ID
        End If

        txtSizeScanInterval.Value = oIntervalFactory.GetIntervalMinutesForDatabase(lDatabaseID, SQLAutoDocLib.ScanSchedule.Type.SizeScan)
        lblLastSizeScan.InnerHtml = FormatDate(oQueueFactory.GetLastQueuedRequest(lDatabaseID, SQLAutoDocLib.ScanSchedule.Type.SizeScan))
        SizeScanReport.Checked = oIntervalFactory.GetReportRequestedForDatabase(lDatabaseID, SQLAutoDocLib.ScanSchedule.Type.SizeScan)

        txtBlockScanInterval.Value = oIntervalFactory.GetIntervalMinutesForDatabase(lDatabaseID, SQLAutoDocLib.ScanSchedule.Type.BlockScan)
        lblLastBlockScan.InnerHtml = FormatDate(oQueueFactory.GetLastQueuedRequest(lDatabaseID, SQLAutoDocLib.ScanSchedule.Type.BlockScan))
        BlockScanReport.Checked = oIntervalFactory.GetReportRequestedForDatabase(lDatabaseID, SQLAutoDocLib.ScanSchedule.Type.BlockScan)

        txtConnectionScanInterval.Value = oIntervalFactory.GetIntervalMinutesForDatabase(lDatabaseID, SQLAutoDocLib.ScanSchedule.Type.ConnectionScan)
        lblLastConnectionScan.InnerHtml = FormatDate(oQueueFactory.GetLastQueuedRequest(lDatabaseID, SQLAutoDocLib.ScanSchedule.Type.ConnectionScan))
        ConnectionScanReport.Checked = oIntervalFactory.GetReportRequestedForDatabase(lDatabaseID, SQLAutoDocLib.ScanSchedule.Type.ConnectionScan)

        txtWaitStateScanInterval.Value = oIntervalFactory.GetIntervalMinutesForDatabase(lDatabaseID, SQLAutoDocLib.ScanSchedule.Type.WaitStateScan)
        lblLastStateScan.InnerHtml = FormatDate(oQueueFactory.GetLastQueuedRequest(lDatabaseID, SQLAutoDocLib.ScanSchedule.Type.WaitStateScan))
        WaitScanReport.Checked = oIntervalFactory.GetReportRequestedForDatabase(lDatabaseID, SQLAutoDocLib.ScanSchedule.Type.WaitStateScan)

        txtSchemaScanInterval.Value = oIntervalFactory.GetIntervalMinutesForDatabase(lDatabaseID, SQLAutoDocLib.ScanSchedule.Type.SchemaScan)
        lblLastSchemaScan.InnerHtml = FormatDate(oQueueFactory.GetLastQueuedRequest(lDatabaseID, SQLAutoDocLib.ScanSchedule.Type.SchemaScan))
        SchemaScanReport.Checked = oIntervalFactory.GetReportRequestedForDatabase(lDatabaseID, SQLAutoDocLib.ScanSchedule.Type.SchemaScan)

    End Sub

    Private Function FormatDate(ByVal sDate As String) As String
        Dim sResult As String = ""

        If IsDate(sDate) Then
            sResult = CDate(sDate).ToShortDateString & "<br/>" & CDate(sDate).ToShortTimeString
        End If

        Return sResult
    End Function

    Private Sub SaveScanIntervals()
        Dim oFactory As New SQLAutoDocLib.ScanSchedule_Factory
        Dim oScan As SQLAutoDocLib.ScanSchedule

        '---Size Scan
        oScan = oFactory.getScheduleForDatabase(moDatabase.ID, SQLAutoDocLib.ScanSchedule.Type.SizeScan)
        If oScan Is Nothing Then
            oScan = New SQLAutoDocLib.ScanSchedule
            oScan.ServerID = moDatabase.ServerID
            oScan.DatabaseID = moDatabase.ID
            oScan.ScanTypeID = SQLAutoDocLib.ScanSchedule.Type.SizeScan
        End If
        oScan.ScanTypeMinutes = txtSizeScanInterval.Value
        oScan.SendReport = SizeScanReport.Checked
        oScan.Save()

        '---Blocks Scan
        oScan = oFactory.GetScheduleForDatabase(moDatabase.ID, SQLAutoDocLib.ScanSchedule.Type.BlockScan)
        If oScan Is Nothing Then
            oScan = New SQLAutoDocLib.ScanSchedule
            oScan.ServerID = moDatabase.ServerID
            oScan.DatabaseID = moDatabase.ID
            oScan.ScanTypeID = SQLAutoDocLib.ScanSchedule.Type.BlockScan
        End If
        oScan.ScanTypeMinutes = txtBlockScanInterval.Value
        oScan.SendReport = BlockScanReport.Checked
        oScan.Save()

        '---Connection Scan
        oScan = oFactory.GetScheduleForDatabase(moDatabase.ID, SQLAutoDocLib.ScanSchedule.Type.ConnectionScan)
        If oScan Is Nothing Then
            oScan = New SQLAutoDocLib.ScanSchedule
            oScan.ServerID = moDatabase.ServerID
            oScan.DatabaseID = moDatabase.ID
            oScan.ScanTypeID = SQLAutoDocLib.ScanSchedule.Type.ConnectionScan
        End If
        oScan.ScanTypeMinutes = txtConnectionScanInterval.Value
        oScan.SendReport = ConnectionScanReport.Checked
        oScan.Save()

        '---Wait States Scan
        oScan = oFactory.GetScheduleForDatabase(moDatabase.ID, SQLAutoDocLib.ScanSchedule.Type.WaitStateScan)
        If oScan Is Nothing Then
            oScan = New SQLAutoDocLib.ScanSchedule
            oScan.ServerID = moDatabase.ServerID
            oScan.DatabaseID = moDatabase.ID
            oScan.ScanTypeID = SQLAutoDocLib.ScanSchedule.Type.WaitStateScan
        End If
        oScan.ScanTypeMinutes = txtWaitStateScanInterval.Value
        oScan.SendReport = WaitScanReport.Checked
        oScan.Save()

        '---Schema Scan
        oScan = oFactory.GetScheduleForDatabase(moDatabase.ID, SQLAutoDocLib.ScanSchedule.Type.SchemaScan)
        If oScan Is Nothing Then
            oScan = New SQLAutoDocLib.ScanSchedule
            oScan.ServerID = moDatabase.ServerID
            oScan.DatabaseID = moDatabase.ID
            oScan.ScanTypeID = SQLAutoDocLib.ScanSchedule.Type.SchemaScan
        End If
        oScan.ScanTypeMinutes = txtSchemaScanInterval.Value
        oScan.SendReport = SchemaScanReport.Checked
        oScan.Save()
    End Sub

    Private Function ValidateFields() As Boolean
        Dim bIsValid As Boolean = True

        errName.Visible = False
        errCString.visible = False

        If Trim(txtName.Text).Length = 0 Then
            errName.InnerText = "You must provide a database name"
            errName.Visible = True

            bIsValid = False
        End If

        If bIsValid = True Then
            Dim sConnectionString As String = MakeConnectionString()

            If Not IsNumeric(DID.Value) OrElse _
                sConnectionString > "" Then
                Dim oScanner As New SQLAutoDocLib.Scanner
                Dim sDBName As String = oScanner.VerifyConnection(sConnectionString)

                If sDBName = "" Then
                    errCString.InnerHtml = "Connection information is incorrect or server or database is off-line. Unable to connect to database using connection string: <b>" & sConnectionString & "</b>"
                    errCString.Visible = True

                    bIsValid = False
                End If
            End If
        End If

        If Not IsNumeric(txtSizeScanInterval.Value) Then
            errSizeScan.InnerText = "An interval for the database/table size scan must be provided."
            errSizeScan.Visible = True

            bIsValid = False
        End If

        If Not IsNumeric(txtBlockScanInterval.Value) Then
            errBlockScan.InnerText = "An interval for the database block count scan must be provided."
            errBlockScan.Visible = True

            bIsValid = False
        End If

        If Not IsNumeric(txtConnectionScanInterval.Value) Then
            errConnectionScan.InnerText = "An interval for the database connection count scan must be provided."
            errConnectionScan.Visible = True

            bIsValid = False
        End If

        If Not IsNumeric(txtWaitStateScanInterval.Value) Then
            errWaitStateScan.InnerText = "An interval for the database wait states scan must be provided."
            errWaitStateScan.Visible = True

            bIsValid = False
        End If

        If Not IsNumeric(txtSchemaScanInterval.Value) Then
            errSchemaScan.InnerText = "An interval for the database/table schema scan must be provided."
            errSchemaScan.Visible = True

            bIsValid = False
        End If

        Return bIsValid
    End Function

    Private Function MakeConnectionString() As String
        Dim sConnectionString As String = ""

        If rdStandard.Checked = True Then
            '---Standard connection
            sConnectionString = "Server=" & lblServerName.Text & ";" & _
                                "Database=" & txtName.Text & ";" & _
                                "Uid=" & txtUserName.Value & ";" & _
                                "Pwd=" & txtPassword.Value & ";"

        ElseIf rdTrusted.Checked = True Then
            '---Trusted connection
            sConnectionString = "Server=" & lblServerName.Text & ";" & _
                                "Database=" & txtName.Text & ";" & _
                                "Trusted_Connection=yes;"

        ElseIf rdFile.Checked = True Then
            '---File connection
            If chkUserInstance.checked = False Then
                sConnectionString = "Server=" & lblServerName.Text & ";" & _
                                    "AttachDbFilename=" & txtFile.Value & ";" & _
                                    "Trusted_Connection=yes;"
            Else
                sConnectionString = "Server=" & lblServerName.Text & ";" & _
                                    "AttachDbFilename=" & txtFile.Value & ";" & _
                                    "integrated security=true;" & _
                                    "user instance=true;"
            End If

        ElseIf rdIP.Checked = True Then
            '---TCPIP connection
            Dim sIP As String = IP1.Value & "." & IP2.Value & "." & IP3.Value & "." & IP4.Value

            sConnectionString = "Data Source=" & sIP & "," & txtPort.Value & ";" & _
                                "Network Library=DBMSSOCN;" & _
                                "Initial Catalog=" & txtName.Text & ";" & _
                                "User ID=" & txtUserName.Value & ";" & _
                                "Password=" & txtPassword.Value & ";"
        End If

        Return sConnectionString
    End Function

    Protected Function FormLabel() As String
        If Not moDatabase Is Nothing Then
            Return "Edit " & moDatabase.Name
        Else
            Return "Add New Database"
        End If
    End Function

    Protected Function ScanMode() As String
        If Not moDatabase Is Nothing Then
            Return moDatabase.Name
        Else
            Return "All"
        End If
    End Function

    Protected Function EditMode() As String
        Return "Database"
    End Function

    Protected ReadOnly Property ServerID() As String
        Get
            If Not moServer Is Nothing Then
                Return moServer.ID
            ElseIf IsPostBack Then
                Return SID.Value
            Else
                Return ""
            End If
        End Get
    End Property

    Protected ReadOnly Property DatabaseID() As String
        Get
            If Not moDatabase Is Nothing Then
                Return moDatabase.ID
            ElseIf IsPostBack Then
                Return DID.Value
            Else
                Return ""
            End If
        End Get
    End Property

    Protected ReadOnly Property DatabaseRevID() As String
        Get
            If Not moDatabase Is Nothing Then
                Return moDatabase.RevID
            ElseIf IsPostBack Then
                Return DBREVID.Value
            Else
                Return ""
            End If
        End Get
    End Property
End Class
